﻿using System;
using System.Collections;
using System.Collections.Generic;


namespace ApplicationGenerator.DataAccess
{
    public class HQLResult
    {

        private List<string> values = new List<string>();
        private List<string> columns = new List<string>();
        private List<Type> types = new List<Type>();
        
        public HQLResult( string query, IList _values )
        {
            columns = GetColumnNames(query);

            for (int i = 0; i < ((object[])_values[0]).Length; i++)
            {
                object[] acs = ((object[])_values[0]);
                values.Add(acs[i].ToString());
            }


            
            //values = _values;
            GetTypes();
        }

        #region properties

        public List<string> Values
        {
            get { return values; }
        }

        public List<string> Columns
        {
            get { return columns; }
        }

        public List<Type> Types
        {
            get { return types; }
        }

        #endregion


        #region helper methods


        public void GetTypes()
        {
            DateTime dt_tmp;

            foreach (string str in values)
            {
                if (str == "true" || str == "false")
                {
                    types.Add(typeof(bool));
                }
                else if (DateTime.TryParse(str, out dt_tmp))
                {
                    types.Add(typeof(DateTime));
                }
                else
                {
                    types.Add(typeof(string));
                }
            }

            
        }

        /// <summary>
        /// Poprawic
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        List<string> GetColumnNames(string input)
        {
            string[] seps = { "from" };
            string[] seps1 = { "select" };

            List<string> columns = new List<string>();
            string[] tab = input.Split(seps, StringSplitOptions.RemoveEmptyEntries);

            if (tab.Length >= 2)
            {

                string[] tab1 = tab[0].Split(seps1, StringSplitOptions.None);
                if (tab1.Length == 2)
                {
                    string[] splits = tab1[1].Split(',');
                    
                    foreach (string str in tab1[1].Split(','))
                    {
                        columns.Add(str.Trim());
                    }
                }

            }
            else
            {
                Console.WriteLine("error");
                return null;
            }

            return columns;
        }

        #endregion

    }
}
